package store.swing.product;

import store.domain.Product;
import store.swing.DefaultTable;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

public class ProductTable extends DefaultTable {
    private static final ProductTableModel TABLE_MODEL = new ProductTableModel();

    public ProductTable() {
        super(TABLE_MODEL);
        initComponents();    }

    private void initComponents() {
        setColumnSize(0, null, 50, null);
        setColumnSize(2, 200, null, null);
        addMouseListener(new TableMouseListener());
    }

    private void setColumnSize(int index, Integer minWidth, Integer maxWidth, Integer preferredWidth) {
        if (minWidth != null) {
            getColumnModel().getColumn(index).setMinWidth(minWidth);
        }
        if (maxWidth != null) {
            getColumnModel().getColumn(index).setMaxWidth(maxWidth);
        }
        if (preferredWidth != null) {
            getColumnModel().getColumn(index).setPreferredWidth(preferredWidth);
        }
    }

    public static ProductTableModel getTableModel() {
        return TABLE_MODEL;
    }

    private class TableMouseListener extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                Integer productId = (Integer) getValueAt(getSelectedRow(), 0);
                List<Product> products = ProductTableModel.getProducts();
                Product selectedProduct = null;
                for (Product product : products) {
                    if (productId.equals(product.getProductId())) {
                        selectedProduct = product;
                        break;
                    }
                }
                new ProductInfoFrame(selectedProduct).setVisible(true);
            }
        }
    }
}
